package org.piaohao.task;

import com.jfinal.plugin.activerecord.Db;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;
import org.piaohao.model.Driver;
import org.piaohao.model.Employee;
import org.piaohao.model.Warn;
import org.piaohao.model.WarnResult;
import org.piaohao.util.string.UUIDGenerator;
import piaohao.util.email.EmailUtil;

/**
 *
 * @author piaohao
 */
public class DriverAgeTask extends TimerTask {

    private Warn warn;

    public DriverAgeTask(Warn warn) {
        this.warn = warn;
    }

    @Override
    public void run() {
        try {
            List<Driver> drivers = Driver.dao.find("select * from t_driver where age>=?", 55);
            Long total = Db.queryLong("select count(*) from t_driver where age>=?", 55);
            String fkIds = "";
            String subject = "驾驶员年龄超过55周岁预警";
            String from = "463168428@qq.com";
            String msg = "<table border='1'>";
            for (int i = 0; i < drivers.size(); i++) {
                Driver driver = drivers.get(i);
                msg += "<tr><td>姓名：</td><td width='100'>" + driver.getStr("name") + "</td><td>身份证：</td><td width='200'>"
                        + driver.getStr("id_card") + "</td><td>电话：</td><td width='200'>"
                        + driver.getStr("cellphone") + "</td><td>年龄：</td><td>"+driver.getInt("age")+"</td></tr>";
                if (i != drivers.size() - 1) {
                    fkIds += driver.getStr("id") + ",";
                } else {
                    fkIds += driver.getStr("id");
                }
            }
            msg += "</table>";
            WarnResult ws = new WarnResult();
            ws.set("id", UUIDGenerator.getUUID());
            ws.set("content", "驾驶员年龄超过55岁预警，" + total + "条记录");
            ws.set("fk_ids", fkIds);
            ws.set("type", 1);
            ws.set("create_time", new Timestamp(new Date().getTime()));
            ws.save();
            String[] empIds = warn.getStr("emp_ids").split(",");
            String[] emails = new String[empIds.length];
            for (int i = 0; i < empIds.length; i++) {
                Employee emp = Employee.dao.findById(empIds[i]);
                emails[i] = emp.getStr("email");
            }
            EmailUtil.sendEmail(subject, msg, from, emails);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
